package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.domain.InvoiceStatusEnums;
import com.yonyou.sto.modules.ims.dto.CancleInvoiceDto;
import com.yonyou.sto.modules.ims.dto.ImsReturnInvoiceParam;
import com.yonyou.sto.modules.ims.dto.InvoiceDto;
import com.yonyou.sto.modules.ims.model.ImsCancleInvoice;
import com.yonyou.sto.modules.ims.model.ImsCancleInvoiceItem;
import com.yonyou.sto.modules.ims.model.ImsInvoice;
import com.yonyou.sto.modules.ims.model.ImsInvoiceItem;
import com.yonyou.sto.modules.ims.service.ImsCancleInvoiceItemService;
import com.yonyou.sto.modules.ims.service.ImsCancleInvoiceService;
import com.yonyou.sto.modules.ims.mapper.ImsCancleInvoiceMapper;
import com.yonyou.sto.modules.ims.service.ImsInvoiceItemService;
import com.yonyou.sto.modules.ims.service.ImsReturnInvoiceService;
import com.yonyou.sto.modules.ums.model.UmsAdmin;
import com.yonyou.sto.modules.ums.model.UmsNcOrg;
import com.yonyou.sto.modules.ums.service.ConfigNameServic;
import com.yonyou.sto.modules.ums.service.UmsAdminOrgRelationService;
import com.yonyou.sto.modules.ums.service.UmsAdminService;
import com.yonyou.sto.modules.ums.service.UmsNcOrgService;
import com.yonyou.sto.modules.ums.util.ImsInvoiceUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.Principal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
*
*/
@Service
public class ImsCancleInvoiceServiceImpl extends ServiceImpl<ImsCancleInvoiceMapper, ImsCancleInvoice>
implements ImsCancleInvoiceService{

    @Resource
    private ImsCancleInvoiceItemService imsCancleInvoiceItemService;

    @Resource
    private UmsAdminService adminService;

    @Resource
    private UmsAdminOrgRelationService umsAdminOrgRelationService;

    @Resource
    private UmsNcOrgService orgService;

    @Resource
    private ImsInvoiceItemService imsInvoiceItemService;

    @Resource
    private ConfigNameServic configNameServic;

    @Resource
    private ImsReturnInvoiceService returnInvoiceSer;

    @Override
    public boolean add(List<ImsInvoice> invoices, Principal principal) {

        for (ImsInvoice invoice: invoices) {
            ImsCancleInvoice ce = new ImsCancleInvoice();
            BeanUtil.copyProperties(invoice, ce, ImsInvoiceUtil.getNullPropertyNames(invoice));
            ce.setId(null);
            ce.setCretime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));//作废时间
            ce.setStatus(InvoiceStatusEnums.CANCEL.getCode());
            ce.setCreatename(principal.getName());//作废人
            baseMapper.insert(ce);
            // save(ce);
            imsCancleInvoiceItemService.add(invoice.getId(), ce.getId());
        }
        return true;
    }

    @Override
    public CommonResult<Map<String, Object>> list(String username, Integer pageSize, Integer pageNum, String billSerial, String billSn, String billNo, String billCode, String sellerName, String buyerName, List<Integer> statusList, String startTime, String endTime, String djlx,String billType,String createName) {
        // 根据开票通知上面的公司和登录用户勾选的公司，当前登录人只展示自己对应的公司开票信息。
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
//        List<Long> partyIds = relationService.getPartyIdsByAdminId(umsAdmin.getId());
        List<String> partyIds = umsAdminOrgRelationService.getNcOrgByAdminId(umsAdmin.getId());


        QueryWrapper<ImsCancleInvoice> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsCancleInvoice> lambda = wrapper.lambda();
        if (!username.equals("admin") ) {
            if (CollUtil.isEmpty(partyIds)){
                Map<String, Object> result = new HashMap<>();
                // mp的分页插件用不了 只能自己分页
                List dtos = new ArrayList<InvoiceDto>();
                result.put("list", dtos);
                result.put("pageNum", pageNum);
                result.put("pageSize", pageSize);
                result.put("total", 0);

                return CommonResult.success(result);
            }
            List<UmsNcOrg> parties = orgService.listByIds(partyIds);
            lambda.in(ImsCancleInvoice::getSellerSn, parties.stream().map(UmsNcOrg::getCode).collect(Collectors.toList()));
        }
//        QueryWrapper<ImsInvoice> wrapper = new QueryWrapper<>();
//        LambdaQueryWrapper<ImsInvoice> lambda = wrapper.lambda();
//
//        if (!username.equals("admin") && CollUtil.isNotEmpty(partyIds)) {
//            List<ImsParty> parties = partyService.listByIds(partyIds);
//            lambda.in(ImsInvoice::getSellerSn, parties.stream().map(ImsParty::getSellerSn).collect(Collectors.toList()));
//        }

        if (StrUtil.isNotEmpty(billSerial)) lambda.like(ImsCancleInvoice::getBillSerial, billSerial);

        if (StrUtil.isNotEmpty(billSn)) lambda.like(ImsCancleInvoice::getBillSn, billSn);

        if (StrUtil.isNotEmpty(billNo)) lambda.like(ImsCancleInvoice::getBillNo, billNo);

        if (StrUtil.isNotEmpty(billCode)) lambda.like(ImsCancleInvoice::getBillCode, billCode);

        if (StrUtil.isNotEmpty(sellerName)) lambda.like(ImsCancleInvoice::getSellerName, sellerName);

        if (StrUtil.isNotEmpty(buyerName)) lambda.like(ImsCancleInvoice::getBuyerName, buyerName);

        if (StrUtil.isNotEmpty(umsAdmin.getNcid())) lambda.like(ImsCancleInvoice::getDef5,umsAdmin.getNcid());

        if (StrUtil.isNotEmpty(billType)) lambda.like(ImsCancleInvoice::getBillType, billType);

        if (StrUtil.isNotEmpty(createName)) lambda.like(ImsCancleInvoice::getCreatename, createName);

        /*if(StrUtil.isNotBlank(umsAdmin.getNcid())){//客服
            String ncId = umsAdmin.getNcid();
            String[] ncIds = ncId.split(",");
            if(ncIds.length==0){
                lambda.in(ImsCancleInvoice::getDef5,ncId);
            }
            lambda.in(ImsCancleInvoice::getDef5,ncIds);
            //lambda.like(ImsCancleInvoice::getDef5,umsAdmin.getNcid());
        }*/

        if (djlx != null) {
            lambda.eq(ImsCancleInvoice::getDjlx, djlx);
        } else {
            lambda.in(ImsCancleInvoice::getDjlx,"fp","ys","lp" );
        }

        lambda.in(ImsCancleInvoice::getStatus, statusList);

        /**
         * allEq	基于 map 内容等于=
         ne	不等于<>
         gt	大于>
         ge	大于等于>=
         lt	小于<
         le	小于等于<=
         */
        if (StrUtil.isNotBlank(startTime))
            lambda.ge(ImsCancleInvoice::getCreateTime, startTime);

        if (StrUtil.isNotBlank(endTime)) {
            if (DateUtil.isSameDay(DateUtil.parse(startTime, "yyyy-MM-dd"), DateUtil.parse(endTime, "yyyy-MM-dd"))) {
                Date date = DateUtil.parse(endTime, "yyyy-MM-dd");
                Date date1 = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
                String format = DateUtil.format(date1, "yyyy-MM-dd");
                lambda.le(ImsCancleInvoice::getCreateTime, format);
            } else {
                lambda.le(ImsCancleInvoice::getCreateTime, endTime);
            }
        }

        lambda.last("order by case status when 3 then 1 when 1 then 2 when 4 then 3 when 7 then 4 else 5 end ,create_time desc");

        List<ImsCancleInvoice> invoices = list(wrapper);

        if (invoices.isEmpty()) {
            return CommonResult.validateFailed("暂无数据");
        }

        List<ImsCancleInvoice> collect = invoices.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        List<String> ids = collect.stream().map(ImsCancleInvoice::getId).collect(Collectors.toList());
        if (ids.isEmpty()) return CommonResult.failed();
        // 查出单据对应的单据明细
        //List<ImsCancleInvoiceItem> items = imsCancleInvoiceItemService.listByBillIds(ids);
        List<ImsCancleInvoiceItem> items = imsCancleInvoiceItemService.list(new LambdaQueryWrapper<ImsCancleInvoiceItem>()
                        .in(ImsCancleInvoiceItem::getManualId, ids)
                        .last(" ORDER BY CAST(DEF6 AS number)")
                //.eq(ImsInvoiceItem::getStatus, InvoiceStatusEnums.NOT.getCode())
        );

        List<CancleInvoiceDto> dtos = new ArrayList<>();
        collect.forEach(i -> {
            CancleInvoiceDto dto = new CancleInvoiceDto();
            BeanUtils.copyProperties(i, dto);
            //dto.setImsCancleInvoiceItems(items.stream().filter(is -> is.getBillSn().equals(dto.getBillSn())).collect(Collectors.toList()));
            dto.setImsCancleInvoiceItems(items.stream().filter(is -> is.getManualId().equals(dto.getId())).collect(Collectors.toList()));
            dto.setCreateTime(i.getCreateTime());
            dtos.add(dto);
        });

        Map<String, Object> result = new HashMap<>();
        // mp的分页插件用不了 只能自己分页
        result.put("list", dtos);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("total", invoices.size());

        return CommonResult.success(result);
    }


    @Override
    public CommonResult invoiceInfo(String id) {
        ImsCancleInvoice i = baseMapper.selectById(id);
        CancleInvoiceDto dto = new CancleInvoiceDto();
        BeanUtil.copyProperties(i, dto);
        //List<ImsInvoiceItem> items = imsInvoiceItemService.listByBillIds(Collections.singletonList(id));
        List<ImsCancleInvoiceItem> invoiceItems = imsCancleInvoiceItemService.list(new LambdaQueryWrapper<ImsCancleInvoiceItem>()
                .eq(ImsCancleInvoiceItem::getManualId, id)
                .eq(ImsCancleInvoiceItem::getStatus, i.getStatus())
                .last(" ORDER BY CAST(DEF6 AS number)")
        );
        List<ImsCancleInvoiceItem> items = getInvoiceItemConfigName(invoiceItems);
        dto.setImsCancleInvoiceItems(items);
        dto.setCreateTime(i.getCreateTime());
        Map<String, Object> result = new HashMap<>();

        List<ImsReturnInvoiceParam> listByBillSn = returnInvoiceSer.getListByBillSn(i.getBillSn());
        result.put("info", dto);
        result.put("re", listByBillSn);
        return CommonResult.success(result);
    }

    public List<ImsCancleInvoiceItem> getInvoiceItemConfigName(List<ImsCancleInvoiceItem> items){
        /*List<ImsCancleInvoiceItem> collect1 = items.stream().map(m -> {
            if (StrUtil.isEmpty(m.getCustmatname())){
                ImsInvoiceItem byId = imsInvoiceItemService.getById(m.getManualId());
                m.setCustmatname(configNameServic.getCustCofigStringName(byId));
            }
            return m;
        }).collect(Collectors.toList());
        imsCancleInvoiceItemService.updateBatchById(collect1);*/
        return items;
    }
}
